<script setup>
import { useQuestionStore } from '@/stores'
import { onMounted, ref, computed } from 'vue'
import {
  getProblemDetailAPI,
  reportAnswerAPI,
  sendAnswerAPI,
  replyAnswerAPI,
  getSubAnswerAPI
} from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const router = useRouter()
const questionStore = useQuestionStore()
const userStore = useUserStore()
const questionInfo = computed(() => questionStore.QuestionInfo)

const answerList = ref([])
const loading = ref(false)

const getSubAnswer = async (id) => {
  const res = await getSubAnswerAPI({ FatherAnswerId: id })
  return res.data
}
const getProblemDetail = async () => {
  loading.value = true
  try {
    const res = await getProblemDetailAPI({ ProblemId: questionInfo.value.Id })
    answerList.value = res.data
    for (const item of answerList.value) {
      item.SubAnswerList = await getSubAnswer(item.Id)
    }
  } catch (error) {
    ElMessage.error('获取问题详情失败')
  } finally {
    loading.value = false
  }
}

const showReport = ref(false)
const reportData = ref({})
const report = (AnswerId, FaBuUserName, AnswerName) => {
  reportData.value = {
    JuBaoUserName: userStore.userInfo.userName,
    FaBuUserName: FaBuUserName,
    Reason: '',
    AnswerId: AnswerId,
    AnswerName: AnswerName
  }
  showReport.value = true
}

const reportAnswer = async () => {
  if (reportData.value.JuBaoUserName === reportData.value.FaBuUserName) {
    ElMessage.error('举报失败，不能举报自己的回答')
    return
  }
  try {
    const res = await reportAnswerAPI(reportData.value)
    if (res.data === 1) {
      ElMessage.success('举报成功')
      showReport.value = false
    } else {
      ElMessage.error('举报失败')
    }
  } catch (error) {
    ElMessage.error('举报过程中出现错误')
  }
}

const showWrite = ref(false)
const newAnswer = ref({})
const writeAnswer = (ProblemId) => {
  newAnswer.value = {
    UserName: userStore.userInfo.userName,
    ProblemId: ProblemId,
    Status: 1,
    AnswerName: '',
    ProblemName: questionInfo.value.ProblemName
  }
  showWrite.value = true
}

const showReply = ref(false)
const newReplayAnswer = ref({})
const replyAnswer = async (AnswerId, Answer) => {
  newReplayAnswer.value = {
    AnswerId: AnswerId,
    UserName: userStore.userInfo.userName,
    ProblemId: questionInfo.value.Id,
    Answer: Answer,
    AnswerName: ''
  }
  showReply.value = true
}
const sendReply = async () => {
  if (!newReplayAnswer.value.AnswerName.trim()) {
    ElMessage.error('回复内容不能为空')
    return
  }
  const res = await replyAnswerAPI(newReplayAnswer.value)
  if (res.data === 1) {
    ElMessage.success('回复成功')
    getProblemDetail()
    showReply.value = false
  } else {
    ElMessage.error('回复失败')
  }
}

const sendAnswer = async () => {
  if (!newAnswer.value.AnswerName.trim()) {
    ElMessage.error('回答内容不能为空')
    return
  }
  try {
    const res = await sendAnswerAPI(newAnswer.value)
    if (res.data === 1) {
      ElMessage.success('发布成功')
      getProblemDetail()
      showWrite.value = false
    } else {
      ElMessage.error('发布失败')
    }
  } catch (error) {
    ElMessage.error('发布过程中出现错误')
  }
}

const convertISO8601ToSimplified = (isoString) => {
  const date = new Date(isoString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const goBack = () => {
  router.go(-1)
}

const viewReplayAnswer = (AnswerId) => {
  document.getElementById('reply' + AnswerId).style.display = 'block'
}

onMounted(() => {
  getProblemDetail()
})
</script>

<template>
  <el-icon
    size="20"
    color="#3670ee"
    style="cursor: pointer; margin: 10px"
    @click="goBack()"
  >
    <ArrowLeftBold />
  </el-icon>
  <span class="title">问题详情</span>

  <div class="question-info" v-if="!loading">
    <div class="problem-name">{{ questionInfo.ProblemName }}</div>
    <div class="card-footer">
      <span class="name">{{ questionInfo.UserName }}</span>
      <el-tag type="success" effect="light" round class="newtag">{{
        questionInfo.Tag
      }}</el-tag>
      <span class="money">{{
        questionInfo.Money == 0 ? '无悬赏' : questionInfo.Money.toFixed(2) + '元悬赏'
      }}</span>
      <span style="padding: 0 20px">{{ questionInfo.account + '条回答' }}</span>

      <span class="time">{{
        convertISO8601ToSimplified(questionInfo.Time)
      }}</span>
    </div>
    <div
      class="more"
      @click="
        report(questionInfo.Id, questionInfo.UserName, questionInfo.ProblemName)
      "
    >
      举报
    </div>
    <el-button
      type="primary"
      class="write-answer"
      @click="writeAnswer(questionInfo.Id)"
    >
      写回答<el-icon class="el-icon--right"><Edit /></el-icon>
    </el-button>
  </div>

  <div v-if="loading">加载中...</div>

  <div v-for="item in answerList" :key="item.Id">
    <div v-if="item.Status != 0" class="card">
      <span class="content">{{ item.AnswerName }}</span>
      <div class="answer-footer">
        <span class="user">{{ item.UserName }}</span>
        <span class="time">{{ convertISO8601ToSimplified(item.Time) }}</span>
        <span class="grade">{{
          item.Gradle == 0 ? '暂无评分' : item.Gradle.toFixed(2) + '分'
        }}</span>
        <span style="margin-left: 380px" @click.stop="viewReplayAnswer(item.Id)"
          >展开回复<el-icon><ArrowDown /></el-icon
        ></span>
        <el-button
          type="primary"
          class="write-answer"
          style="margin-left: 20px"
          @click="replyAnswer(item.Id, item.AnswerName)"
        >
          回复<el-icon class="el-icon--right"><Edit /></el-icon>
        </el-button>
      </div>
      <div
        class="more"
        @click="report(item.Id, item.UserName, item.AnswerName)"
      >
        举报
      </div>
    </div>
    <div
      :id="'reply' + item.Id"
      v-for="item2 in item.SubAnswerList"
      :key="item2.Id"
      class="reply"
      style="width: 90%; margin-left: 90px"
    >
      <div class="card">
        <span class="content">{{ item2.AnswerName }}</span>
        <div class="answer-footer">
          <span class="user">{{ item2.UserName }}</span>
          <span class="time">{{ convertISO8601ToSimplified(item2.Time) }}</span>
        </div>
      </div>
    </div>
    <el-divider />
  </div>

  <el-dialog v-model="showReply" title="回复评论" width="500">
    <el-form :model="newReplayAnswer">
      <el-form-item label="评论：">
        <el-input
          v-model="newReplayAnswer.Answer"
          autocomplete="off"
          disabled
        />
      </el-form-item>
      <el-form-item label="输入回复：">
        <el-input v-model="newReplayAnswer.AnswerName" autocomplete="off" />
      </el-form-item>
      <el-button type="primary" @click="sendReply()">发布回复</el-button>
    </el-form>
  </el-dialog>

  <el-dialog v-model="showReport" title="举报回答" width="500">
    <el-form :model="reportData">
      <el-form-item label="回答发布人:">
        <el-input
          v-model="reportData.FaBuUserName"
          autocomplete="off"
          disabled
        />
      </el-form-item>
      <el-form-item label="回答:">
        <el-input v-model="reportData.AnswerName" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item label="举报原因:">
        <el-input v-model="reportData.Reason" autocomplete="off" />
      </el-form-item>
      <el-button type="primary" @click="reportAnswer()">举 报</el-button>
    </el-form>
  </el-dialog>

  <el-dialog v-model="showWrite" title="发布回答" width="500">
    <el-form :model="newAnswer">
      <el-form-item label="问题：">
        <el-input v-model="newAnswer.ProblemName" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item label="输入回答：">
        <el-input v-model="newAnswer.AnswerName" autocomplete="off" />
      </el-form-item>
      <el-button type="primary" @click="sendAnswer()">发布回答</el-button>
    </el-form>
  </el-dialog>
</template>

<style scoped>
.reply {
  display: none;
}
.question-info {
  position: relative;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin: 15px 0;
  padding: 20px;
  border-radius: 10px;
  background-color: #fff;
}
.problem-name {
  font-size: 24px;
  margin: 10px 0;
  font-weight: 700;
  color: #333;
}
.title {
  font-size: 24px;
  line-height: 24px;
  color: #3670ee;
  font-weight: 700;
  margin-bottom: 20px;
}
.name {
  margin: 0 15px;
}
.newtag {
  margin-right: 10px;
}
.time {
  font-size: 14px;
  margin-left: 10px;
  color: #999;
}
.money {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c; /* 悬赏金额颜色 */
}
.write-answer {
  margin: 15px 0;
}
.card {
  position: relative;
  margin: 10px 0;
  padding: 15px;
  border-radius: 10px;
  background-color: #f7f9fc;
  transition: transform 0.2s;
}
.card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.content {
  margin: 10px;
  font-size: 20px;
  font-weight: 500;
}
.answer-footer {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.user {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}
.grade {
  margin-left: 15px;
  color: #999;
}
.more {
  position: absolute;
  right: 20px;
  top: 10px;
  background-color: #e7e7e7;
  width: 60px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  font-size: 14px;
  border-radius: 15px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.more:hover {
  background-color: #d0d0d0;
}
</style>
